<?php
namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class User {
    public $userObj = null;

    public function __construct()
    {
        $this->userObj = new UserModel();
    }

    public function login($data) {
        $redisCode = cache(config('redis.code_pre').$data['phone_number']);
        if (empty($redisCode) || $redisCode != $data['code']){
//            throw new Exception('不存在该验证码',-1009);
        }
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        if (empty($user)){
            // 不存在的走这个新增
            $username = '测试用户-'.$data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => config('status.mysql.table_normal'),
            ];
            try {
                $this->userObj->save($userData);
                $userId = $this->userObj->id;
            } catch (\Exception $e) {
                throw new Exception('数据库内部异常');
            }
        }else{
            // 如果存在就走更新 todo 可以把用户最后一次登录时间和登录ip记录一下
            $userId = $user->id;
            $username = $user->username;
        }


        // 生成token
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            'id'=>$userId,
            'username'=>$username
        ];
        $res = cache(config('redis.token_pre').$token, $redisData, Time::userLoginExpiresTime($data['type']));
        return $res ? ['token'=>$token, 'username'=>$username] : false;
    }

    public function getNormalUserById($id) {
//        try {
//            $user = $this->userObj->getUserById($id);
//        } catch (DataNotFoundException $e) {
//        } catch (ModelNotFoundException $e) {
//        } catch (DbException $e) {
//        }
        $user = $this->userObj->getUserById($id);
        if (empty($user) || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return $user->toArray();
    }

    public function getNormalUserByUsername($username) {
        $user = $this->userObj->getUserByUsername($username);
        if (empty($user) || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return $user->toArray();
    }

    public function update($id, $data) {
        $user = $this->getNormalUserById($id);
        if (empty($user)){
            throw new \think\Exception('不存在该用户');
        }
        $userResult = $this->getNormalUserByUsername($data['username']);
        if ($userResult && $userResult['id'] != $id){
            throw new \think\Exception('该用户已经存在请重新设置');
        }
        return $this->userObj->updateById($id, $data);
    }
}